package tcm.com.gistone.api.restController;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.api.service.WordService;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.Directory;
import tcm.com.gistone.database.entity.Section;
import tcm.com.gistone.database.mapper.DirectoryMapper;
import tcm.com.gistone.database.mapper.SectionMapper;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.EdatResult;
import tcm.com.gistone.util.Item;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangfan on 2017/8/12.
 */
@RestController("apiBookController")
@RequestMapping("api/book")
public class BookController {

    @Autowired
    private DirectoryMapper dm;
    @Autowired
    private SectionMapper sm;
    @Autowired
    private GetBySqlMapper getBySqlMapper;

    @Autowired
    WordService wordService;


    @RequestMapping(value = "getImgList", method = RequestMethod.POST)
    public EdatResult getImgList(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("------");
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));

            Integer bookId = data.getInt("bookId");;
            String sql = "SELECT  section_id,image_Url FROM  tb_directory WHERE book_id="+bookId+" and image_Url IS NOT  NULL  and image_Url !=\"\"";
            List<Map> result = getBySqlMapper.findRecords(sql);
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }
    /**
     * 获取所有古籍信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "allBookInfo", method = RequestMethod.POST)
    public EdatResult getAllBookInfo(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("------");
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            String sql = "select * from tb_bookinfo where 1=1 and status=7";
            if (null!= specialId) {
                sql = sql + " and special_id =" + specialId;
            }
            List<Map> result = getBySqlMapper.findRecords(sql);
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /**
     * 查询某本书某一页的所有段落，关键词为中医的道地关系
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "queryPlaceByBookAndPagenum", method = RequestMethod.POST)
    public EdatResult queryPlaceByBookAndPagenum(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            int bookId = data.getInt("bookId");
            int number = data.getInt("number");
            String sql = "SELECT tb_ancient_modern_place.name,tb_ancient_modern_place.ancient , tb_ancient_modern_place.modern" +
                    " FROM tb_knowledge  INNER  JOIN  tb_ancient_modern_place on tb_knowledge.knowledge_name=tb_ancient_modern_place.name and tb_knowledge.genuine=tb_ancient_modern_place.ancient" +
                    " WHERE  book_id="+bookId+" and knowledge_name in" +
                    " (SELECT  tb_word.word from tb_ws_relation_copy,tb_word" +
                    " where tb_ws_relation_copy.word_id =tb_word.word_id and section_id in" +
                    " (select section_id from tb_section where book_id ="+bookId+" and number ="+number+"))";
            List<Map> maps = this.getBySqlMapper.findRecords(sql);


            return EdatResult.ok(maps);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }


    /**
     * 按关键字查询书籍信息
     * 模糊查询
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "queryBookInfo", method = RequestMethod.POST)
    public EdatResult queryBookInfo(HttpServletRequest request,
                                    HttpServletResponse response) {

        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            int offset = data.getInt("offset");
            int pageSize = data.getInt("pageSize");
            String keyWord = data.getString("keyWord");
//            String dynasty = data.getString("dynasty");
            String sql = "select * from tb_bookinfo where 1=1 and status=7 ";
            if (null!= specialId) {
                sql = sql + " and special_id =" + specialId + " ";
            }
            if (!keyWord.isEmpty()) {
                sql = sql + " and  book_name like  '%" + keyWord + "%' "
                        + "or author like  '%" + keyWord + "%' "
                        + "or section like  '%" + keyWord + "%' "
                        + "or location like  '%" + keyWord + "%' "
                        + "or appose_name like  '%" + keyWord + "%' "
                        + "or dynasty like  '%" + keyWord + "%' ";

            }

            sql = sql + "limit " + offset + "," + pageSize;
            List<Map> result = getBySqlMapper.findRecords(sql);
            System.out.println(result.toString());
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /**
     * 按关键字查询书籍信息
     * 精确查询
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "queryBookInfoWithOper", method = RequestMethod.POST)
    public EdatResult queryBookInfoWithOper(HttpServletRequest request,
                                            HttpServletResponse response) {

        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }
            int offset = data.getInt("offset");
            int pageSize = data.getInt("pageSize");
            String bookname = data.getString("bookname");
            String con1 = data.getString("con1");
            String author = data.getString("author");
            String con2 = data.getString("con2");
            String type = data.getString("type");
            String con3 = data.getString("con3");
//            String con5 =data.getString("con5");

            String abst = data.getString("abstract");
            String con4 = data.getString("con4");
            String dynasty = data.getString("dynasty");

            String sql = "select * from tb_bookinfo where 1=1 and status=7 ";
            if (null != specialId) {
                sql = sql + " and special_id =" + specialId + " ";
            }
            if (!bookname.isEmpty()) {
                sql = sql + " and book_name like  '%" + bookname + "%'  ";
                if (!author.isEmpty()) {
                    sql =sql + con1 + "  author like  '%" + author + "%'  ";
                }
                if (!dynasty.isEmpty()) {
                    sql =sql + con2 + "  dynasty like  '%" + dynasty + "%'  ";

                }
                if (!type.isEmpty()) {
                    sql =sql + con3 + "  type like  '%" + type + "%'  ";
                }
                if (!abst.isEmpty()) {
                    sql = sql +con4 + "  book_abstract like  '%" + abst + "%'  ";
                }


            }else{
                if (!author.isEmpty()) {
                    con1 =" and";
                    sql =sql + con1 + "  author like  '%" + author + "%'  ";
                    if (!dynasty.isEmpty()) {
                        sql = sql +con2 + "  dynasty like  '%" + dynasty + "%'  ";

                    }
                    if (!type.isEmpty()) {
                        sql = sql +con3 + "  type like  '%" + type + "%'  ";
                    }
                    if (!abst.isEmpty()) {
                        sql = con4 + "  book_abstract like  '%" + abst + "%'  ";
                    }
                }else{

                    if (!dynasty.isEmpty()) {

                            con2 =" and";
                            sql = sql +con2 + "  dynasty like  '%" + dynasty + "%'  ";


                        if (!type.isEmpty()) {
                            sql = sql +con3 + "  type like  '%" + type + "%'  ";
                        }
                        if (!abst.isEmpty()) {
                            sql =sql + con4 + "  book_abstract like  '%" + abst + "%'  ";
                        }

                    }else{
                        if (!type.isEmpty()) {
                            con3 =" and";
                            sql = sql +con3 + "  type like  '%" + type + "%'  ";
                            if (!abst.isEmpty()) {
                                sql = sql +con4 + "  book_abstract like  '%" + abst + "%'  ";
                            }
                        }else{
                            if (!abst.isEmpty()) {
                                con4 =" and";
                                sql =sql + con4 + "  book_abstract like  '%" + abst + "%'  ";
                            }
                        }


                    }
                }




            }
        /*    sql = sql + (bookname.isEmpty() ? " " : "   book_name like  '%" + bookname + "%'  ");
            sql = sql + (author.isEmpty() ? " " : con2 + "  author like  '%" + author + "%'  ");
            sql = sql + (type.isEmpty() ? " " : con3 + "  type like  '%" + type + "%'  ");
            sql = sql + (abst.isEmpty() ? " " : con4 + "  abstract like  '%" + abst + "%'  ");
            sql = sql + (dynasty.isEmpty() ? " " : con5 + "  dynasty like  '%" + dynasty + "%'  ");
           */
            sql = sql + " limit " + offset + "," + pageSize;
            List<Map> result = getBySqlMapper.findRecords(sql);
            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }


    /**
     * 根据书籍id获取书籍信息bookInfo与书籍最大页码pageNum
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "getBookInfo", method = RequestMethod.POST)
    public EdatResult getBookInfo(HttpServletRequest request,
                                  HttpServletResponse response) {

        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            System.out.println(data.toString());
            int bookId = data.getInt("bookId");
            Map map = new HashMap();
            String sql = "select * from tb_bookinfo where  status=7 and book_id =" + bookId;
            map.put("bookInfo", this.getBySqlMapper.findRecords(sql).get(0));
            sql = "select max(number) as number from tb_section where book_id =" + bookId;
            map.put("pageNum", this.getBySqlMapper.findrows(sql));
            return EdatResult.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }




    /*获取古籍目录*/
    @RequestMapping(value = "getDirectory", method = RequestMethod.POST)
    public EdatResult getDirectory(HttpServletRequest request,
                                   HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request
                    .getParameter("data"));
            long bookId = data.getLong("bookId");
            Map<String, Object> map = new HashMap();
            List<Directory> list = dm.selectByBookIdAndLevel(bookId, 0);
            for (Directory dir : list) {
                map.put("children", setDir(dir.getId()));
                map.put("name", dir.getName());
                map.put("sectionId", dir.getSectionId());
                map.put("id", dir.getId());
                map.put("pageNum", getPageNum(dir.getSectionId()) + "");
                map.put("parentId", dir.getParentId());
            }
            return EdatResult.build(0, "success", map);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    @RequestMapping(value = "getBookinfoByDynasty", method = RequestMethod.GET)
    public EdatResult getBookinfoByDynasty(HttpServletRequest request,
                                       HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String dynasty = data.getString("dynasty");
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }

//
            String sql = "select * from tb_bookinfo where  status=7 and dynasty ='" + dynasty + "' ";
            if (null != specialId) {
                sql = sql + " and special_id =" + specialId + " ";
            }
            List<Map> childList = this.getBySqlMapper.findRecords(sql);

            return EdatResult.ok(childList);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }



    @RequestMapping(value = "getBookinfoByType", method = RequestMethod.GET)
    public EdatResult getBookinfoByType(HttpServletRequest request,
                                           HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            int typeId = data.getInt("typeId");
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }

//
            String sql = "select a.*,b.type_name from tb_bookinfo a ,tb_book_group b,tb_group_book c where a.book_id=c.book_id AND b.type_name =c.type_name and b.type_id="+ typeId ;
            if (null != specialId) {
                sql = sql + " and a.special_id =" + specialId + " ";
            }
            List<Map> result = this.getBySqlMapper.findRecords(sql);

            return EdatResult.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }


    /*获取以朝代区分目录，左侧导航--*/
    @RequestMapping(value = "getBookByDynasty", method = RequestMethod.GET)
    public EdatResult getBookByDynasty(HttpServletRequest request,
                                   HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request.getParameter("data"));
            String dynasty = data.getString("dynasty");
            Integer specialId = null;
            if (data.has("specialId")) {
                specialId = data.getInt("specialId");

            }

            List<Item> voItemList = new ArrayList<Item>();
            Item root = new Item();
            String sql = "select * from tb_bookinfo where  status=7 and dynasty ='" + dynasty + "' ";
            if (null != specialId) {
                sql = sql + " and special_id =" + specialId + " ";
            }
            if(dynasty.length()==2){
                root.setText(dynasty+"书籍列表");
            }else{
                root.setText(dynasty+"代书籍列表");
            }

            root.setId(1);
            root.setLeaf(false);
            List<Item> nodes = new ArrayList<>();
            List<Map> childList = this.getBySqlMapper.findRecords(sql);
            if (childList.size() > 0) {

                for (Map map : childList) {
                    System.out.println(map.toString());
                    Item child = new Item();
                    child.setId((long)map.get("book_id"));
                    child.setText("【"+map.get("book_name").toString()+"】");
                    child.setLeaf(true);
                    nodes.add(child);
                }

            }
            root.setNodes(nodes);
            voItemList.add(root);
            return EdatResult.ok(voItemList);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }


    /*获取sectionId所在书籍的页码数*/
    private Integer getPageNum(long sectionId) {
        Integer pageNum = null;

        Section section = sm.selectByPrimaryKey(sectionId);
        if (null != section) {
            pageNum = section.getNumber();
        }

        return pageNum;

    }

    //遍历父id
    public List<Map> setDir(long id) {
        List list = new ArrayList();
        List<Directory> tem = dm.selectByParentId(id);
        if (tem.size() < 1) {
            return null;
        }
        for (Directory dir : tem) {
            Map<String, Object> map = new HashMap<>();
            map.put("children", setDir(dir.getId()));
            map.put("name", dir.getName());

            map.put("pageNum", getPageNum(dir.getSectionId()) + "");
            map.put("sectionId", dir.getSectionId());

//            sm.selectByPrimaryKey(dir.getSectionId()).getNumber();

            map.put("id", dir.getId());
            map.put("parentId", dir.getParentId());
            list.add(map);
        }
        return list;
    }


}
